<template>
  <div class="body page-miH page-bgBack" style="display: flex; padding: 0">
    <div class="leftBox">
      <div style="display: flex; justify-content: space-between; align-items: center">
        <div style="font-size: 16px; font-weight: 500; color: #252525">渠道分组</div>
        <a-popover title="没有权限" v-if="allGroupList.jurisdiction === 3">
          <template slot="content">
            <div>您的权限不足，只有渠<br />道总管理才可创建分组</div>
          </template>
          <a-button type="link" disabled><a-icon type="plus" style="color: #a6a8b4" /> </a-button>
        </a-popover>
        <a-button style="padding: 0" type="link" v-else @click="showAddGroup"><a-icon type="plus" style="color: #000000" /> </a-button>
      </div>
      <a-input-search
        placeholder="搜索分组名称/分组主管"
        v-model="groupNameOrUserName"
        style="width: 216px; margin-top: 12px"
        allow-clear
        @search="onSearch"
      />
      <div
        v-if="allGroupList"
        @click="showSiteItem"
        :class="allGroupList.selectIng ? 'itemHoverIng' : 'itemHover'"
        style="
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 12px;
          margin-top: 10px;
          border-bottom: 1px solid #e8e8e8;
        "
      >
        <div style="font-size: 14px; font-weight: 400; color: #000000">
          {{ allGroupList.name ? allGroupList.name + " (" + allGroupList.number + ")" : "--" }}
        </div>
        <a-popover title="没有权限" v-if="allGroupList.jurisdiction === 3">
          <template slot="content">
            <div>您的权限不足，只有渠<br />道总管理才可维护此组</div>
          </template>
          <a-icon style="color: #a6a8b4; cursor: pointer" type="setting" theme="filled" />
        </a-popover>
        <a-icon @click="showEditGroup(allGroupList)" v-else style="cursor: pointer" type="setting" theme="filled" />
      </div>
      <div v-if="allGroupList.channelGroupVOList && allGroupList.channelGroupVOList.length">
        <div
          v-for="(item, index) in allGroupList.channelGroupVOList"
          :key="index"
          :class="item.selectIng ? 'itemHoverIng' : 'itemHover'"
          @click="showItem(item, index)"
          style="
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 12px 12px 24px;
            border-bottom: 1px solid #e8e8e8;
          "
        >
          <div style="font-size: 14px; font-weight: 400">{{ item.name + " (" + item.number + ")" }}</div>
          <a-icon v-if="item.name !== '默认分组'" type="setting" theme="filled" style="cursor: pointer" @click="showEditGroup(item)" />
        </div>
      </div>
    </div>

    <div class="rightBox" v-if="showItemDetail">
      <div>
        <div class="titleBox">
          <div style="display: flex; justify-content: space-between">
            <div style="font-size: 18px; font-weight: 500; color: #3c3d43">{{ selectItem.name }}</div>
            <a-button @click="showEmp" :disabled="allGroupList.jurisdiction === 3 && selectItem.isAll === true">分组管理员</a-button>
          </div>
          <div
            v-if="allGroupList.jurisdiction !== 3 || selectItem.isAll !== true"
            style="font-size: 12px; font-weight: 400; color: #a6a8b4"
          >
            {{ selectItem.describe }}
          </div>
        </div>
        <div class="action">
          <div>
            <a-input-search allow-clear placeholder="搜索渠道名称/联系电话" style="width: 225px" @search="inputChange" />
            <city placeholder="所在地区" :level="3" @change="handleCityForSeach($event)" style="margin-left: 12px" />
          </div>
          <div style="display: flex">
            <a-button type="primary" @click="showAdd" style="margin-right: 18px">
              <a-icon type="plus" />
              新增渠道
            </a-button>

            <!-- <a-upload style="margin-right:18px" ref="upload" :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload"> -->
            <a-button block @click="goUpload" style="margin-right: 18px">批量导入</a-button>
            <!-- </a-upload> -->
            <a-button @click="exportFile" :disabled="!dataList.length"> 全部导出 </a-button>
            <!-- <a-button type="primary" @click="download2" style="margin-left:18px">
            下载导入模板
          </a-button> -->
          </div>
        </div>
        <div class="tableBox">
          <a-table
            :loading="loading"
            rowKey="id"
            :columns="columns"
            :data-source="dataList"
            :pagination="pagination"
            @change="handleTableChange"
          >
            <template slot="groupName" slot-scope="text">
              <span>
                {{ text ? text : "默认分组" }}
              </span>
            </template>
            <a slot="numberPeople" slot-scope="text, record" @click="showDetail(record)">
              <span class="primary">
                {{ text }}
              </span>
            </a>
            <a slot="action" slot-scope="text, record">
              <span class="primary" @click="handleEditOk(record)"> 编辑 </span>
              <a-button
                type="link"
                size="small"
                style="margin-left: 17px"
                :disabled="record.numberPeople > 0"
                class="primary"
                @click="showDelete(record)"
              >
                删除
              </a-button>
            </a>
          </a-table>
        </div>
        <div class="drawerBox">
          <a-modal :title="title" :visible="visible" @ok="handleAddOK" @cancel="onClose">
            <a-form-model ref="ruleForm" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-form-model-item
                label="所属分组"
                ref="channelGroupId"
                prop="channelGroupId"
                :rules="{
                  required: true,
                  message: '请选择'
                }"
              >
                <a-select v-model="form.channelGroupId" placeholder="请选择">
                  <a-select-option v-for="role in allGroupList.channelGroupVOList" :key="role.id" :value="role.id">{{
                    role.name
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item
                ref="name"
                label="渠道名称"
                prop="name"
                :rules="{
                  required: true,
                  message: '请输入'
                }"
              >
                <a-input v-model="form.name" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item
                ref="phone"
                label="联系电话"
                prop="phone"
                :rules="{
                  required: true,
                  validator: validatorPhone
                }"
              >
                <a-input v-model="form.phone" placeholder="请输入" :disabled="title === '编辑渠道'" />
              </a-form-model-item>
              <a-form-model-item
                label="所在地区"
                ref="address"
                prop="address"
                :rules="{
                  required: false,
                  message: '请选择'
                }"
              >
                <city :default-value="form.address" :level="3" @change="handleCity($event)" />
              </a-form-model-item>
              <a-form-model-item
                ref="idcard"
                label="身份证号"
                prop="idcard"
                :rules="{
                  validator: validatorIdCard
                }"
              >
                <a-input v-model="form.idcard" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item ref="name" label="银行卡号" prop="name">
                <a-input-number v-model="form.bankNo" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item
                label="用工单位"
                ref="isAllChildCompany"
                prop="isAllChildCompany"
                :rules="{
                  required: true,
                  message: '请选择'
                }"
              >
                <a-switch v-model="form.isAllChildCompany" checked-children="全部" un-checked-children="自选" default-checked />
              </a-form-model-item>
              <a-form-model-item v-if="!form.isAllChildCompany" label="分管单位">
                <a-button @click="showModal"> 共{{ targetKeys.length }}个<a-icon type="right" /> </a-button>
                <a-modal v-model="treeVisible" title="选择分管单位" @ok="handleOk" width="800px">
                  <a-transfer
                    :list-style="{
                      width: '350px',
                      height: '400px'
                    }"
                    :operations="['添加', '删除']"
                    class="tree-transfer"
                    :data-source="dataSource"
                    :target-keys="targetKeys"
                    :render="(item) => item.title"
                    :show-select-all="false"
                    @change="onTransChange"
                  >
                    <template slot="children" slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }">
                      <a-tree
                        defaultExpandAll
                        style="height: 300px; overflow-y: scroll"
                        v-if="direction === 'left'"
                        blockNode
                        checkable
                        checkStrictly
                        :replaceFields="replaceFields"
                        :checkedKeys="[...selectedKeys, ...targetKeys]"
                        :tree-data="treeData"
                        @check="
                          (_, props) => {
                            onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                          }
                        "
                        @select="
                          (_, props) => {
                            onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                          }
                        "
                      />
                    </template>
                  </a-transfer>
                </a-modal>
              </a-form-model-item>
            </a-form-model>
          </a-modal>
        </div>
        <a-modal title="删除" :visible="deleteVisible" @ok="deleteOk" @cancel="handleCancel">
          <div style="display: flex; justify-content: center; align-items: center">
            <a-icon type="question-circle" style="font-size: 28px; color: #6a66f6" />
            <div style="font-size: 16px; font-weight: 500; color: #3c3d43; line-height: 20px; margin-left: 20px">
              您确定要删除该渠道吗？一旦删除不可恢复
              <!-- ，该渠道下招工的人员将自动变为无渠道人员 -->
            </div>
          </div>
        </a-modal>
      </div>

      <a-modal :title="title2 + '招工详情'" :visible="detailVisible" :footer="null" @cancel="detailCancel" :width="800">
        <div>
          <a-input-search
            allow-clear
            placeholder="搜索姓名/手机号/身份证号"
            style="width: 235px"
            @search="inputChange2"
            v-model="nameOrPhoneOrIdcard"
          />
          <a-select allowClear placeholder="请选择" @change="selectCheck2" v-model="status" style="width: 175px; margin-left: 20px">
            <a-select-option value="1"> 已接到 </a-select-option>
            <a-select-option value="2"> 已安排 </a-select-option>
            <a-select-option value="3"> 已面试 </a-select-option>
            <a-select-option value="4"> 已入职 </a-select-option>
            <a-select-option value="5"> 已离职 </a-select-option>
          </a-select>
        </div>
        <div class="tableBox">
          <a-table
            :scroll="{ x: 600 }"
            rowKey="id"
            :columns="columns2"
            :data-source="dataList2"
            :pagination="pagination2"
            @change="handleTableChange2"
          >
            <a slot="joinDate" slot-scope="text" style="cursor: text; color: #595959">
              {{ text ? moment(text).format("YYYY-MM-DD") : "--" }}
            </a>
            <a slot="companyName" slot-scope="text" style="cursor: text; color: #595959">
              {{ text ? text : "--" }}
            </a>
            <a slot="status" slot-scope="text">
              <div
                style="
                  text-align: center;
                  width: 50px;
                  height: 20px;
                  background: rgba(255, 166, 0, 0.1);
                  border-radius: 2px;
                  border: 1px solid #ffa600;
                  font-size: 11px;
                  font-weight: 400;
                  color: #ffa600;
                "
                v-if="text === 2"
              >
                已安排
              </div>
              <div
                style="
                  text-align: center;
                  width: 50px;
                  height: 20px;
                  background: rgba(106, 102, 246, 0.1);
                  border-radius: 2px;
                  border: 1px solid #6a66f6;
                  font-size: 11px;
                  font-weight: 400;
                  color: #6a66f6;
                "
                v-if="text === 1"
              >
                已接到
              </div>
              <div
                style="
                  text-align: center;
                  width: 50px;
                  height: 20px;
                  background: rgba(36, 205, 170, 0.1);
                  border-radius: 2px;
                  border: 1px solid #24cdaa;
                  font-size: 11px;
                  font-weight: 400;
                  color: #24cdaa;
                "
                v-if="text === 3"
              >
                已面试
              </div>
              <div
                style="
                  text-align: center;
                  width: 50px;
                  height: 20px;
                  background: rgba(66, 130, 255, 0.1);
                  border-radius: 2px;
                  border: 1px solid #4282ff;
                  font-size: 11px;
                  font-weight: 400;
                  color: #4282ff;
                "
                v-if="text === 4"
              >
                已入职
              </div>
              <div
                style="
                  text-align: center;
                  width: 50px;
                  height: 20px;
                  background: rgba(0, 0, 0, 0.04);
                  border-radius: 2px;
                  border: 1px solid rgba(0, 0, 0, 0.15);
                  font-size: 11px;
                  font-weight: 400;
                  color: #767885;
                "
                v-if="text === 5"
              >
                已离职
              </div>
            </a>
          </a-table>
        </div>
      </a-modal>
    </div>
    <div v-else class="rightBox" style="padding: 0">
      <a-row class="head">
        <a-icon type="left" @click="showItemDetail = true" />
        <div class="left2" style="cursor: pointer" @click="showItemDetail = true">
          <slot name="subTitle">返回</slot>
        </div>
        <slot>{{ selectItem.name }}分组管理员</slot>
      </a-row>
      <div style="padding: 24px">
        <div style="display: flex; justify-content: space-between; align-items: center">
          <a-input-search allow-clear placeholder="搜索管理员姓名" v-model="onSearchEmpName" style="width: 200px" @search="onSearchEmp" />
          <a-button
            type="primary"
            :disabled="(allGroupList.jurisdiction === 2 && selectItem.isAll === true) || allGroupList.jurisdiction === 3"
            @click="isChooseStaff = true"
            >新增管理员</a-button
          >
        </div>
        <a-table rowKey="id2" :columns="columnsEmp" :data-source="dataListEmp" :pagination="false" style="margin-top: 24px">
          <a slot="action" slot-scope="text, record">
            <a-button
              type="link"
              :disabled="!record.id || (allGroupList.jurisdiction === 2 && selectItem.isAll === true) || allGroupList.jurisdiction === 3"
              @click="deleteEmp(record)"
            >
              删除
            </a-button>
          </a>
        </a-table>
        <employee-select
          :show.sync="isChooseStaff"
          :default-selected-keys="empList"
          :selected-list.sync="empList"
          @change="onEmployeeSelectChange"
          :groupId="selectItem.id"
        />
      </div>
    </div>
    <a-drawer :width="450" :title="groupTitle" placement="right" :visible="groupVisible" @close="onGroupClose">
      <div>
        <div style="display: flex; justify-content: center; align-items: center">
          <div style="color: #fa5051; margin-right: 4px">*</div>
          <div style="font-size: 14px; font-weight: 400; color: #55565d">分组名称</div>
          <a-input :disabled="isLevel" v-model="groupName" placeholder="请输入分组名称" style="width: 248px; margin-left: 10px"></a-input>
        </div>
        <div class="flex-start-center" style="margin-top: 32px">
          <div style="font-size: 14px; font-weight: 400; color: #55565d; margin-left: 9px">分组说明</div>
          <a-textarea
            v-model="groupDescribe"
            :maxLength="150"
            placeholder="最多150个字"
            style="width: 248px; margin-left: 10px; min-height: 120px"
          ></a-textarea>
        </div>
      </div>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
          display: 'flex',
          justifyContent: 'center'
        }"
      >
        <a-button
          v-if="groupTitle === '编辑分组' && !selectItem.isAll && allGroupList.jurisdiction !== 3"
          :style="{
            marginRight: '8px',
            color: allGroupList.jurisdiction !== 3 ? '#FA5051' : 'none',
            borderColor: allGroupList.jurisdiction !== 3 ? '#FA5051' : 'none'
          }"
          @click="deleteGroup"
        >
          删除
        </a-button>
        <a-button :style="{ marginRight: '8px' }" @click="onGroupClose"> 取消 </a-button>
        <a-button type="primary" @click="addGroupOk"> 确定 </a-button>
      </div>
    </a-drawer>
  </div>
</template>
<script>
const columns = [
  {
    title: "所属分组",
    dataIndex: "groupName",
    key: "groupName",
    width: 100,
    scopedSlots: { customRender: "groupName" }
  },
  {
    title: "渠道名称",
    dataIndex: "name",
    key: "name",
    width: 100
  },
  {
    title: "联系电话",
    dataIndex: "phone",
    key: "phone",
    width: 120
  },
  {
    title: "所在地区",
    dataIndex: "addressCopy",
    key: "addressCopy",
    width: 120
  },
  {
    title: "身份证号",
    dataIndex: "idcard",
    key: "idcard",
    width: 120
  },
  {
    title: "银行卡号",
    dataIndex: "bankNo",
    key: "bankNo",
    width: 140
  },
  {
    title: "渠道招工人数",
    dataIndex: "numberPeople",
    key: "numberPeople",
    width: 100,
    scopedSlots: { customRender: "numberPeople" }
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    scopedSlots: { customRender: "action" },
    align: "left",
    width: 150
  }
];
const columns2 = [
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
    width: 100
  },
  {
    title: "联系电话",
    dataIndex: "phone",
    key: "phone",
    width: 120
  },
  {
    title: "最近入职时间",
    dataIndex: "joinDate",
    key: "joinDate",
    width: 150,
    scopedSlots: { customRender: "joinDate" }
  },
  {
    title: "当前用工单位",
    dataIndex: "companyName",
    key: "companyName",
    width: 150,
    scopedSlots: { customRender: "companyName" }
  },
  {
    title: "人员状态",
    dataIndex: "status",
    key: "status",
    width: 100,
    scopedSlots: { customRender: "status" }
  }
];
const columnsEmp = [
  {
    title: "管理员",
    dataIndex: "userName",
    key: "userName",
    width: 100,
    scopedSlots: { customRender: "userName" }
  },
  {
    title: "手机号",
    dataIndex: "phone",
    key: "phone",
    width: 100,
    scopedSlots: { customRender: "phone" }
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: 100,
    align: "center",
    scopedSlots: { customRender: "action" }
  }
];

import { mapState } from "vuex";
import {
  getChannels2,
  addChannels,
  editChannels,
  deleteChannels,
  getPrePersonnel,
  findCompanyGroup,
  getByUserId,
  getHrRole,
  addGroup,
  getAllGroup,
  editGroup,
  deleteGroup,
  getUserByGroupId,
  addGroupEmp,
  deleteEmp
} from "@/api/outsourcing/outsourcing";
import UploadMixin from "xqjr-plugin-common/UploadOrExport/uploadMixin";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
import { AreaPicker as city } from "xqjr-plugin-common";
import axios from "axios";
import qs from "qs";
const mixin2 = new ExportMixin();
const mixin = new UploadMixin();
let treeData = [];
function isChecked(selectedKeys, eventKey) {
  return selectedKeys.indexOf(eventKey) !== -1;
}
function handleTreeData(data, targetKeys = []) {
  data.forEach((item) => {
    item["disabled"] = targetKeys.includes(item.key);
    if (item.children) {
      handleTreeData(item.children, targetKeys);
    }
  });
  return data;
}
export default {
  mixins: [mixin, mixin2],
  data() {
    const validatorPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入"));
      } else {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("手机号格式不正确!"));
        } else {
          callback();
        }
      }
    };
    const validatorIdCard = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        if (
          !/^((^[HMhm](\d{8}|\d{10})$)|(^(\d{8}|^[a-zA-Z]{1}(\d{7}))$)|(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx]$)))$/.test(
            value
          )
        ) {
          callback(new Error("身份证号格式不正确!"));
        } else {
          callback();
        }
      }
    };
    return {
      replaceFields: {
        children: "companyList",
        title: "name",
        key: "id",
        value: "id"
      },
      groupTitle: "添加分组",
      targetKeys: [],
      empList: [],
      rolesList: [],
      columnsEmp,
      isChooseStaff: false,
      groupDescribe: undefined,
      groupName: undefined,
      loading: false,
      validatorPhone,
      showItemDetail: true,
      validatorIdCard,
      columns2,
      onSearchEmpName: undefined,
      title2: null,
      channelId: null,
      title: "新增渠道",
      params: {
        templateName: "channelInfoImportTemplate.xlsx"
      },
      url2: `/hr/api/v1/excel/template/download`,
      excelName: "渠道上传模板.xlsx",
      visible: false,
      deleteVisible: false,
      childCompanyIdList: [],
      employerIdList: [],
      dataList: [],
      dataListEmp: [],
      dataList2: [],
      treeData2: [],
      allGroupList: {},
      columns,
      detailVisible: false,
      form: {},
      dataSource: [],
      groupId: "",
      groupNameOrUserName: null,
      isLevel: false,
      status: null,
      selectItem: {},
      channelName: null,
      params2: {},
      nameOrPhoneOrIdcard: null,
      labelCol: { span: 8 },
      addressForSeach: undefined,
      treeVisible: false,
      wrapperCol: { span: 12 },
      groupVisible: false,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        personalPeriod: null,
        editCompanyName: null,
        ticketRecord: null,
        receivableRecord: null,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      pagination2: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        personalPeriod: null,
        editCompanyName: null,
        ticketRecord: null,
        receivableRecord: null
      }
    };
  },
  watch: {
    "form.idcard"(val) {
      this.form.idcard = val ? val.toUpperCase() : null;
    }
  },
  components: {
    city,
    EmployeeSelect: () => import("./addEmp")
  },
  computed: {
    ...mapState(["common"]),
    cityList() {
      return this.common.cityList;
    },
    areaList() {
      return this.common.areaList;
    },
    treeData: {
      get() {
        return treeData;
      },
      set(val) {
        return handleTreeData(treeData, this.targetKeys);
      }
    }
  },
  created() {
    this.getHrRole();
    this.geRoles();
    this.findCompanyGroup();
    this.action = `/hr/api/v1/channels/importChannel`;
    this.getAllGroupList();
  },
  methods: {
    handleCityForSeach(e) {
      this.pagination.current = 1;
      this.pagination.pageSize = 10;

      this.addressForSeach = e.value[e.value.length - 1];
      this.getChannelsList();
    },
    deleteEmp(e) {
      var that = this;
      this.$confirm({
        title: "确认删除吗?",
        onOk() {
          deleteEmp({
            managerId: e.id,
            jurisdiction: that.selectItem.name === "默认分组" ? 1 : that.selectItem.isAll ? 2 : -1
          }).then((res) => {
            that.$notification["success"]({
              message: "success",
              description: "删除成功"
            });
            that.getUserByGroupId();
          });
        },
        class: "test"
      });
    },

    onEmployeeSelectChange(e) {
      var userIdList = [];
      e.forEach((item) => {
        userIdList.push(item.id);
      });
      addGroupEmp({
        channelGroupId: this.selectItem.id,
        userIdList: userIdList
      }).then((res) => {
        this.$notification["success"]({
          message: "success",
          description: "新增成功"
        });
        this.getUserByGroupId();
        this.empList = [];
      });
    },
    onSearchEmp() {
      this.getUserByGroupId();
    },
    showEmp() {
      this.showItemDetail = false;
    },
    onSearch() {
      this.getAllGroupList();
    },
    showItem(item, indexs) {
      this.showItemDetail = true;
      this.allGroupList.selectIng = false;
      this.allGroupList.channelGroupVOList.forEach((item, index) => {
        if (index === indexs) {
          item.selectIng = true;
        } else {
          item.selectIng = false;
        }
      });

      this.selectItem = item;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.getChannelsList();
      this.getUserByGroupId();
    },
    getUserByGroupId() {
      getUserByGroupId({
        groupId: this.selectItem.id,
        jurisdiction: this.selectItem.name === "默认分组" ? 1 : this.selectItem.isAll ? 2 : -1,
        userName: this.onSearchEmpName
      }).then((res) => {
        this.dataListEmp = res.data;
      });
    },
    showSiteItem() {
      this.showItemDetail = true;
      this.selectItem = this.allGroupList;
      this.allGroupList.selectIng = true;
      this.allGroupList.channelGroupVOList.forEach((item, index) => {
        item.selectIng = false;
      });
      this.selectItem.isAll = true;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.getChannelsList();
      this.getUserByGroupId();
    },
    getAllGroupList() {
      getAllGroup({
        groupNameOrUserName: this.groupNameOrUserName
      }).then((res) => {
        this.allGroupList = res.data;
        this.allGroupList.selectIng = true;
        this.selectItem = this.allGroupList;
        this.selectItem.isAll = true;
        this.getChannelsList();
        this.getUserByGroupId();
      });
    },
    updateAllGroupList() {
      getAllGroup({
        groupNameOrUserName: this.groupNameOrUserName
      }).then((res) => {
        this.allGroupList = res.data;
        this.allGroupList.channelGroupVOList.forEach((item, index) => {
          if (item.id === this.selectItem.id) {
            item.selectIng = true;
          } else {
            item.selectIng = false;
          }
        });
      });
    },
    addGroupOk() {
      if (!this.groupName) {
        this.$message.warning("分组名称必填！");
      } else {
        if (this.groupTitle === "添加分组") {
          addGroup({
            name: this.groupName,
            level: 2,
            describe: this.groupDescribe
          })
            .then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "新增成功"
              });
              this.getAllGroupList();
              this.groupVisible = false;
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        } else if (this.groupTitle === "编辑分组") {
          editGroup({
            name: this.groupName,
            level: this.isLevel ? 1 : 2,
            describe: this.groupDescribe,
            id: this.groupId
          })
            .then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "编辑成功"
              });
              this.getAllGroupList();
              this.groupVisible = false;
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        }
      }
    },
    deleteGroup() {
      deleteGroup(this.groupId)
        .then((res) => {
          this.$notification["success"]({
            message: "success",
            description: "删除成功"
          });
          this.getAllGroupList();
          this.groupVisible = false;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    showAddGroup() {
      this.groupVisible = true;
      this.groupTitle = "添加分组";
      this.groupName = undefined;
      this.groupDescribe = undefined;
      this.isLevel = false;
    },
    showEditGroup(item) {
      this.isLevel = false;
      this.groupVisible = true;
      this.groupTitle = "编辑分组";
      this.groupName = item.name;
      this.groupDescribe = item.describe;
      this.groupId = item.id;
      if (item.jurisdiction) {
        this.isLevel = true;
      } else {
        this.isLevel = false;
      }
    },
    getHrRole() {
      getHrRole().then((res) => {
        this.hrRoleId = res.data.id;
      });
    },
    beforeUpload(file) {
      if (this.fileList.length > 0) {
        this.$message("最多只能上传一个");
        return false;
      }
      this.fileList = [...this.fileList, file];
      if (this.fileList && this.fileList.length > 0) {
        const { fileList } = this;
        const formData = new FormData();
        fileList.forEach((file) => {
          formData.append("file", file);
        });
        this.uploading = true;

        axios({
          url: this.action,
          method: "post",
          data: formData,
          headers: this.headers
        }).then((res) => {
          this.getChannelsList();
          this.$store.dispatch("hr/loadChannelsList");
          this.reset();
          this.uploading = false;
        });
      } else {
        this.reset();
        this.handleUploadError();
      }
      return false;
    },
    download2() {
      const token = this.$store.state.auth.token;
      axios({
        url: this.url2,
        params: this.params,
        paramsSerializer: (param) => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", this.excelName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    goUpload() {
      this.$router.push({
        path: "/admin/management/account/upload"
      });
    },
    exportFile() {
      this.params2 = {
        nameOrPhone: this.channelName ? this.channelName : null,
        level: this.selectItem.isAll ? 1 : 2,
        channelGroupId: this.selectItem.id
      };
      this.url = `/hr/api/v1/channels/channelInfoExport`;
      this.excelName = `渠道详情.xlsx`;
      this.getDownload();
    },
    getDownload() {
      axios({
        url: this.url,
        params: this.params2,
        paramsSerializer: (param) => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: this.token
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", this.excelName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 递归替换字段
    addTreeSlot(data) {
      if (!data) {
        return [];
      }
      data.forEach((el) => {
        if (el.type === "site") {
          el.disabled = true;
          el.key = "-1";
        } else {
          el.key = el.id;
        }
        el.title = el.name;

        this.addTreeSlot(el.companyList);
      });
      return data;
    },
    getByUserId() {
      getByUserId({
        userId: this.detail.id
      }).then((res) => {
        this.choseEmp = res.data.isAllChildCompany;
        this.targetKeys = res.data.companyIds.concat(res.data.groupIds);
      });
    },
    handleOk(e) {
      this.treeVisible = false;
    },
    findCompanyGroup() {
      findCompanyGroup()
        .then((res) => {
          this.treeData2 = this.addTreeSlot(res.data);
          if (this.treeData2[0] && this.treeData2[0].type === "site") {
            this.disabled2 = false;
          } else {
            this.disabled2 = true;
          }
          treeData = this.treeData2;
          this.flatten(this.treeData2);
          if (this.editor) {
            this.detail = this.$route.query;
            this.getByUserId();
            this.copyDetail = { ...this.$route.query };
            if (!this.detail.employerIdList) {
              this.detail.employerIdList = [];
            }
          }
          const formKey = {};
          Object.keys(this.form).forEach((key) => {
            formKey[key] = this.detail[key];
          });
          this.form = {
            ...this.form,
            ...formKey
          };
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    flatten(list) {
      if (list !== null) {
        list.forEach((item) => {
          this.dataSource.push(item);
          this.flatten(item.companyList);
        });
      }
    },
    onChecked(_, e, checkedKeys, itemSelect) {
      const { eventKey } = e.node;
      itemSelect(eventKey, !isChecked(checkedKeys, eventKey));
    },
    showModal() {
      this.targetKeys = JSON.parse(JSON.stringify(this.targetKeys));

      this.treeVisible = true;
    },
    onTransChange(targetKeys) {
      this.targetKeys = targetKeys;
    },
    // 获取账号角色列表
    geRoles() {
      this.$request({
        method: "GET",
        url: `/hr/api/v1/hrRoles/listAll`,
        params: { subjectType: "company" }
      }).then(({ data }) => {
        this.rolesList = data;
      });
    },
    // 查询详情
    showDetail(e) {
      this.nameOrPhoneOrIdcard = undefined;
      this.status = undefined;
      this.title2 = e.name;
      this.channelId = e.id;
      this.pagination2.pageSize = 10;
      this.pagination2.current = 1;
      this.getPrePersonnelList();
    },
    inputChange2(e) {
      this.pagination2.pageSize = 10;
      this.pagination2.current = 1;
      this.nameOrPhoneOrIdcard = e;
      this.getPrePersonnelList();
    },
    selectCheck2(e) {
      this.status = e;
      this.pagination2.pageSize = 10;
      this.pagination2.current = 1;
      this.getPrePersonnelList();
    },
    getPrePersonnelList() {
      getPrePersonnel({
        isShowOtherInfo: true,
        "orders[0].property": "status",
        "orders[0].desc": false,
        nameOrPhoneOrIdcard: this.nameOrPhoneOrIdcard ? this.nameOrPhoneOrIdcard : null,
        status: this.status ? this.status : null,
        channelId: this.channelId ? this.channelId : null,
        pageNo: this.pagination2.current,
        pageSize: this.pagination2.pageSize
      }).then((res) => {
        this.detailVisible = true;
        this.dataList2 = res.data.entities;
        this.pagination2.total = res.data && res.data.entityCount;
      });
    },
    detailCancel() {
      this.detailVisible = false;
    },
    // 删除渠道
    showDelete(e) {
      this.deleteId = e.id;
      this.deleteVisible = true;
    },
    deleteOk(e) {
      deleteChannels(this.deleteId).then((res) => {
        this.$notification["success"]({
          message: "success",
          description: "删除成功"
        });
        this.pagination.pageSize = 10;
        this.pagination.current = 1;
        this.deleteVisible = false;
        this.getChannelsList();
        this.updateAllGroupList();
        this.$store.dispatch("hr/loadChannelsList");
      });
    },
    handleCancel() {
      this.deleteVisible = false;
    },
    handleCity(e) {
      var addressChinese = e.label.join("/");
      this.form.address = `${e.value[e.value.length - 1]},` + addressChinese;
    },
    // 编辑渠道
    handleEditOk(e) {
      this.targetKeys = [];
      if (e.companyIds && e.companyIds.length) {
        this.targetKeys = this.targetKeys.concat(e.companyIds);
      }
      if (e.groupIds && e.groupIds.length) {
        this.targetKeys = this.targetKeys.concat(e.groupIds);
      }
      this.title = "编辑渠道";
      this.form = { isAllChildCompany: e.isAllChildCompany };
      this.visible = true;
      console.log(e);
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
        this.form = JSON.parse(JSON.stringify(e));
      });
    },
    // 新增编辑渠道点击确定
    handleAddOK() {
      this.childCompanyIdList = [];
      this.employerIdList = [];
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.targetKeys.forEach((item, index) => {
            this.dataSource.forEach((item2, index2) => {
              if (item === item2.id && item2.type === "group") {
                this.childCompanyIdList.push(item);
              }
              if (item === item2.id && item2.type === "company") {
                this.employerIdList.push(item);
              }
            });
          });
          for (var i = 0; i < this.childCompanyIdList.length; i++) {
            for (var j = i + 1; j < this.childCompanyIdList.length; j++) {
              if (this.childCompanyIdList[i] === this.childCompanyIdList[j]) {
                // 如果第一个等于第二个，splice方法删除第二个
                this.childCompanyIdList.splice(j, 1);
                j--;
              }
            }
          }
          for (var o = 0; o < this.employerIdList.length; o++) {
            for (var p = o + 1; p < this.employerIdList.length; p++) {
              if (this.employerIdList[o] === this.employerIdList[p]) {
                // 如果第一个等于第二个，splice方法删除第二个
                this.employerIdList.splice(p, 1);
                p--;
              }
            }
          }
          if (this.title === "新增渠道") {
            addChannels({
              ...this.form,
              password: this.form.phone,
              hrRoleId: this.hrRoleId,
              userName: this.form.name,
              childCompanyIdList: this.childCompanyIdList,
              employerIdList: this.employerIdList
            }).then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "添加成功"
              });
              this.visible = false;
              this.getChannelsList();
              this.updateAllGroupList();
            });
          }
          if (this.title === "编辑渠道") {
            if (this.form.address && this.form.address.indexOf(",") === -1) {
              const values = this.buildValue(this.getLastAreaId(this.form.address));
              const labels = values.map((item) => item.label);
              this.form.address = `${this.form.address},${labels.join("/")}`;
            }
            editChannels({
              ...this.form,
              childCompanyIdList: this.childCompanyIdList,
              employerIdList: this.employerIdList
            }).then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "编辑成功"
              });
              this.visible = false;
              this.getChannelsList();
            });
          }
          this.$store.dispatch("hr/loadChannelsList");
        } else {
          return false;
        }
      });
    },
    buildValue(id, needRecursion = true) {
      id = parseInt(id);
      const index = this.common.areaSourceList.findIndex((item) => item.id === parseInt(id));
      if (index > -1) {
        const item = this.common.areaSourceList[index];
        const val = {
          value: id,
          label: item.name
        };
        if (needRecursion && item.parentId > 0) {
          return this.buildValue(item.parentId).concat([val]);
        } else {
          return [val];
        }
      }
      return [];
    },
    // 分页查询渠道
    getChannelsList() {
      this.loading = true;
      getChannels2({
        nameOrPhone: this.channelName ? this.channelName : null,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        channelGroupId: this.selectItem.isAll ? undefined : this.selectItem.id,
        level: this.selectItem.isAll ? 1 : 2,
        address: this.addressForSeach
      }).then((res) => {
        this.loading = false;
        this.dataList = res.data.entities;
        this.dataList.forEach((element) => {
          if (element.address) {
            if (element.address) {
              var addressCopy = element.address.split(",")[0];
              element.address = addressCopy;
              const values = this.buildValue(this.getLastAreaId(addressCopy));
              const labels = values.map((item) => item.label);
              element.addressCopy = labels.join("/");
            }
          }
        });
        this.pagination.total = res.data && res.data.entityCount;
      });
    },
    getLastAreaId(values) {
      if (Array.isArray(values)) {
        return values[values.length - 1];
      } else {
        return values.split(",").slice(-1)[0];
      }
    },
    // 控制新增编辑框
    showAdd() {
      this.title = "新增渠道";
      this.visible = true;
      this.$nextTick(() => {
        // this.$refs.ruleForm.clearValidate();
        this.form = { channelGroupId: this.selectItem.isAll ? undefined : this.selectItem.id, isAllChildCompany: true };
        this.$refs.ruleForm.resetFields();
        this.targetKeys = [];
      });
    },
    onClose() {
      this.visible = false;
      this.form = {};
    },
    onGroupClose() {
      this.groupVisible = false;
    },
    // 搜索框
    inputChange(e) {
      this.channelName = e;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.getChannelsList();
    },
    // 分页器
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getChannelsList();
    },
    handleTableChange2(pagination, filters, sorter) {
      this.pagination2.current = pagination.current;
      this.pagination2.pageSize = pagination.pageSize;
      this.getPrePersonnelList();
    }
  }
};
</script>

<style lang="scss" scoped>
.leftBox {
  width: 264px;
  border-right: 1px solid #e8e8e8;
  min-height: 490px;
  padding: 12px 24px;
  .itemHover:hover {
    color: var(--primary);
    background: var(--primary10);
  }
  .itemHoverIng {
    color: var(--primary);
    background: var(--primary10);
  }
}
.rightBox {
  width: 100%;
  padding: 24px;
  .titleBox {
    width: 100%;
    height: 96px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 24px;
  }
}
.tableBox {
  margin-top: 24px;
}
.body {
  padding: 24px;
  .title {
    font-size: 18px;
    font-weight: 400;
    color: #333333;
    padding-bottom: 24px;
  }
  .action {
    display: flex;
    justify-content: space-between;
    margin-top: 24px;
  }
  .tableBox {
    margin-top: 24px;
  }
}
.head {
  background-color: #fff;
  .anticon-left {
    z-index: 3;
    left: 24px;
    position: absolute;
    color: #595959;
    font-size: 20px;
    margin-top: 20px;
  }
  .left2 {
    z-index: 3;
    left: 50px;
    position: absolute;
    color: #595959;
    font-size: 16px;
  }
  font-size: 16px;
  color: #000;
  font-weight: 500;
  text-align: center;
  line-height: 60px;
  height: 60px;
  border-bottom: 1px solid #e8e8e8;
}
</style>
